package com.hfy.shop.listener;

import com.alibaba.fastjson.JSON;
import com.hfy.model.vo.PopOrderVo;
import com.hfy.shop.mapper.GoodMapper;
import com.hfy.shop.mapper.OrderMapper;
import com.rabbitmq.client.Channel;
import constants.RabbitConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

import static constants.StatusConstants.ORDER_STATUS_OVERTIME;

/**
 * @ author 韩
 * time: 2024/9/12 17:42
 */

@Component
@Slf4j
public class ExpireOrderListener {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private GoodMapper goodMapper;

    @RabbitListener(queues = { RabbitConstants.DELAY_ORDER_QUEUE })
    public void listenDlQueue(String msg, Message message, Channel channel) {

        log.error("我要开始喽！");
        // 把msg转成对象
        PopOrderVo popOrderVo = null;
        try {
            popOrderVo = JSON.parseObject(msg, PopOrderVo.class);
        } catch (Exception e) {
            throw new RuntimeException("请调用符合规定的api，类型转换错误，无法转换为PopOrderVo");
        }

        // 自动取消订单逻辑
        LocalDateTime now = LocalDateTime.now();
        Integer orderId = popOrderVo.getOrderId();
        Integer goodId = popOrderVo.getGoodId();
        // 修改订单状态
        orderMapper.finishOrder(orderId, now, ORDER_STATUS_OVERTIME);
        // 把锁了的库存释放
        goodMapper.unLockStore(goodId);
        log.error("我结束喽！");

    }

}
